#include <iostream>
#include <string>
#include "Reactor.hpp"
#include "Channel.hpp"
#include "Listener.hpp"
#include "Log.hpp"
#include "Common.hpp"
#include "Protocol.hpp"
#include "NetCal.hpp"

static void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    LogModule::ConsoleLogStrategy();
    uint16_t port = std::stoi(argv[1]);

    std::shared_ptr<Cal> cal = std::make_shared<Cal>();

    std::shared_ptr<Protocal> protocal = std::make_shared<Protocal>([&cal](Request &req) -> Response{
        return cal->Excute(req);
    });

    std::shared_ptr<Connection> conn = std::make_shared<Listener>(port);
    conn->RegisterHandler([&protocal](std::string &inbuffer) -> std::string{
        std::string package;
        if(!protocal->Decode(inbuffer,&package))
            return std::string();
        std::string Response_str = protocal->Exectue(package);
       return Response_str;
    });

    std::unique_ptr<Reactor> R = std::make_unique<Reactor>();
    R->AddConection(conn);

    R->Loop();
    return 0;
}